<?php
class Favourite_model extends CI_Model {

	function __construct()
    {
        parent::__construct();
    }
	/**
	 * 新增
	 */
	public function add($data) {   
		
		$this->db->insert("favourites", $data);
		return $this->db->insert_id();
	}
	
	public function remove($id) {
		$this->db->where('id', $id);
		$this->db->delete('favourites'); 
	}
	
	public function is_favourited($user_id, $target_id, $target_type) {
		$sql = "select count(*) as total from favourites where user_id=" . $user_id .
				" and target_id=" . intval($target_id) . " and target_type='" . $target_type . "'";
		$result = $this->db->query($sql)->row_array();
		return $result['total'];
	}
	public function find_favourite_stories($user_id, $offset = 0, $limit = 20) {
		$sql = " select e.*, u.nickname from favourites f 
		left join emergencies e on e.id = f.target_id
		left join users u on u.id=e.created_by 
		where f.user_id=" . $user_id . " and f.target_type='story' order by created desc ";
		$sql .= " limit " . $offset . "," . $limit;
		return $this->db->query($sql)->result_array();
	}

	public function get_count_favourite_story($user_id) {
		$sql = " select count(*) as total from favourites where target_type='story' and user_id=" . $user_id;
		$result = $this->db->query($sql)->row_array();
		return $result['total'];
	}
	
	public function find_favourite_experts($user_id) {
		$sql = " select e.* from favourites f left join experts e on e.id = f.target_id
		where f.user_id=" . $user_id . " and f.target_type='expert'";
		return $this->db->query($sql)->result_array();
	}

	public function get_count_favourite_expert($user_id) {
		$sql = " select count(*) as total from favourites where target_type='expert' and user_id=" . $user_id;
		$result = $this->db->query($sql)->row_array();
		return $result['total'];
	}
}